package cc.endsearch.util;

import cc.endsearch.po.TextMessage;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageUtil {
    /**
     *@Author xcl
     *@Date 2017/11/7 0:05
     *@Description
     * 把微信传来的xml格式数据转为集合形式
     */
    public static Map<String,String> amlToMap(HttpServletRequest request) throws IOException, DocumentException {

        Map<String,String> map = new HashMap<String, String>();
        //创建reader对象 用来读取xml
        SAXReader reader = new SAXReader();
        //从request中获取输入流
        InputStream inputStream = request.getInputStream();
        //从inputStream中获取数据
        Document doc = reader.read(inputStream);
        Element root = doc.getRootElement();
        List<Element> elList = root.elements();
        //从xml获取键值对，保存在map中
        for (Element ele: elList
             ) {
            map.put(ele.getName(),ele.getText());
        }
        inputStream.close();
        return map;
    }
    /**
     *@Author xcl
     *@Date 2017/11/7 0:15
     *@Description
     * 将文本对象转为xml对象
     */
    public static String textMessageToXml(TextMessage textMessage){
        //此处出现异常，原因是：返回给微信的xml 根元素为xml  而此处默认为文件路径
        XStream stream = new XStream();
        //跟换根元素
        stream.alias("xml",textMessage.getClass());
        return stream.toXML(textMessage);
    }
}
